package com.guw.TestThread;

//银行取钱的模拟
public class TestSyn2 {
    public static void main(String[] args) {
        //新建账户
        Account account1 = new Account(10000, "zhangsan");
        //同一账户新建两个取钱的线程
        Drawing drawing1 = new Drawing(account1, 100);
        Drawing drawing2 = new Drawing(account1, 350);
        //线程启动
        new Thread(drawing1).start();
        new Thread(drawing2).start();
        System.out.println(account1.balance);
    }
}

//账户类
class Account {
    int balance;
    String name;
    public Account(int balance, String name) {
        this.balance = balance;
        this.name = name;
    }
}
//取钱的类
class Drawing implements Runnable {
    Account account;
    int drawingMoney;

    public Drawing(Account account, int drawingMoney) {
        this.account = account;
        this.drawingMoney = drawingMoney;
    }
    //取钱的方法
    public void getMoney() {
        if (account.balance >= drawingMoney) {
            account.balance = account.balance - drawingMoney;
        } else {
            System.out.println("余额不足!");
            return;
        }
    }
    //预留存钱的方法
    public void setMoney() {
        account.balance = account.balance + drawingMoney;
    }

    @Override
    public void run() {
        //锁在这里放才有效果,锁的是账户信息!!
        synchronized (account) {
            //当余额大于取款数时,取钱
            while (account.balance >= drawingMoney) {
                getMoney();
                System.out.println(account.balance);
                try {
                    //每次动作停100毫秒
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
